using Furion;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using EasyAdmin.Admin.Entity.DbContext;
using EasyAdmin.Admin.Application.Services;
using EasyAdmin.Admin.Application.Services.Impl;
using EasyAdmin.Admin.WebApi.Middleware;
using SqlSugar;

var builder = WebApplication.CreateBuilder(args).Inject();

// 注册控制器服务
builder.Services.AddControllers().AddInject();

// 注册 SqlSugar 数据库服务
builder.Services.AddSqlSugar(builder.Configuration);

// 注册应用服务
builder.Services.AddScoped<ISysUserService, SysUserService>();
builder.Services.AddScoped<ISysRoleService, SysRoleService>();
builder.Services.AddScoped<ISysMenuService, SysMenuService>();

// 配置跨域
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", policy =>
    {
        policy.WithOrigins(builder.Configuration.GetSection("Cors:Origins").Get<string[]>())
              .WithMethods(builder.Configuration.GetSection("Cors:Methods").Get<string[]>())
              .WithHeaders(builder.Configuration.GetSection("Cors:Headers").Get<string[]>())
              .AllowCredentials();
    });
});

// 配置 JWT 认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
            ValidAudience = builder.Configuration["JwtSettings:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecurityKey"]))
        };
    });

// 添加控制器
builder.Services.AddControllers();

// 配置 Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 配置 HTTP 请求管道
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

// 添加 Furion 中间件
app.UseInject(string.Empty);

// 添加全局异常处理中间件
app.UseGlobalExceptionHandling();

// app.UseHttpsRedirection();

// 启用跨域
app.UseCors("CorsPolicy");

// 启用认证和授权
app.UseAuthentication();
app.UseAuthorization();

// 映射控制器路由
app.MapControllers();

// 初始化数据库
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
    SqlSugarDbContext.InitializeDatabase(db);
}

app.Run();